package com.jdplat.jdm.core.web.controller;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisConnectionException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jdplat.jdm.core.WebContext;
import com.jdplat.jdm.core.redis.Redis;
import com.jdplat.jdm.core.spring.SpringContext;
import com.jdplat.jdm.core.utils.ClassUtil;
import com.jdplat.jdm.core.web.utils.ActionRequest;
import com.jdplat.jdm.core.web.utils.Bundle;
import com.jdplat.jdm.core.web.utils.DataUtil;
import com.jdplat.jdm.core.web.utils.DateUtils;
import com.jdplat.jdm.core.web.utils.IPUtil;
import com.jdplat.jdm.core.web.utils.RedisUtil;
import com.jdplat.jdm.core.web.utils.RequestData;
import com.jdplat.jdm.core.web.utils.WeatherUtils;
import com.jdplat.jdm.web.entity.User;
import com.jdplat.jdm.web.shiro.UserUtil;

/**
 * Created by qirp on 2016/11/15.
 */
public class BaseController<Entity, PK extends Serializable> extends SpringContext<Entity, PK> {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected String urlTitle;

    @ModelAttribute
    private void init(HttpServletRequest request,HttpServletResponse response){
        this.request = request;
        this.response = response;
    }
    //
	public HttpServletResponse getResponse() {
		return WebContext.getInstance().getResponse();
	}

	public HttpServletRequest getRequest() {
		return WebContext.getInstance().getRequest();
	}
	//回去get参数
	public String getPara(String name) {
		return getRequest().getParameter(name);
	}

	public String getPara(String name, String defaultValue) {
		return ActionRequest.getPara(name, defaultValue, getRequest());
	}

	/*public Integer getParaToInt(String name) {
		return parseInt((getRequest().getParameter(name)));
	}

	public Long getParaToLong(String name) {
		return parseLong(getRequest().getParameter(name));
	}

	public Double getParaToDouble(String name) {
		return parseDouble(getRequest().getParameter(name));
	}*/

	public String[] getParaValues(String key) {
		return getRequest().getParameterValues(key);
	}

/*	public String getParaFormatDate(String name) {
		return parseDate(getRequest().getParameter(name));
	}*/
	//获取请求参数
	public Map<String, Object> getRequestList(HttpServletRequest request){
		return new RequestData(request).getRequestList();
	}
	//返回报文数据
	public void renderData(JSONObject datas){
		ActionRequest.renderData(datas.toString(), response);
	}
	
	//ModelAndView
	private ModelAndView view;
	public ModelAndView getModelViewInstances(){
		if(null == view){
			view = new ModelAndView();
		}
		return view;
	}
	
	public ModelAndView getSuccess(String viewName) {
		ModelAndView modelAndView = getModelViewInstances();
		modelAndView.setViewName(viewName);
		return modelAndView;
	}

	public <T> ModelAndView getSuccess(String viewName, T newinstances) {
		return getSuccess(viewName).addAllObjects(convertObj2Map(newinstances));
	}
	public ModelAndView getModelView() {
		return getModelViewInstances();
	}

	public Map<String, Object> getModel() {
		return getModelView().getModel();
	}

	public ModelAndView getSuccess(String viewName, String attributeName, Object attributeValue) {
		return this.getSuccess(viewName).addObject(attributeName, attributeValue);
	}

	public void addObject(String attributeName, Object attributeValue) {
		getModelViewInstances().addObject(attributeName, attributeValue);
	}

	public void addAllObjects(Map<String, ?> modelMap) {
		getModelViewInstances().addAllObjects(modelMap);
	}
	
	
	
	
	
	
	
	//以下为一些常用的工具
	public <T> Map<String, Object> convertObj2Map(T obj) {
		return ClassUtil.convertObj2Map(obj);
	}
	// -----------------catche-----------------------
	/**
	 * 拿到一个字符串
	 * @param catchKey
	 * @return
	 */
	public String getCatch(String catchKey) {
		return Redis.getCatch(catchKey, getJedis());
	}
    /**
     * 拿到对象
     * @param catchKey
     * @return
     */
	public Object getCatch(Object catchKey) {
		return Redis.getCatch(catchKey, getJedis());
	}

	/**
	 * 判断缓存是否存在
	 */
	public boolean existsCatch(String catchKey) {
		return Redis.existsCatch(catchKey, getJedis());
	}

	/**
	 * 放置缓存信息
	 */
	public void putCatch(String catchKey, String catchValue) {
		Redis.putCatch(catchKey, catchValue, getJedis());
	}
	
	public void putCatch(String catchKey, String catchValue , int exprise) {
		Redis.putCatch(catchKey, catchValue, exprise , getJedis());
	}

	/**
	 * redis链接检测
	 */
	private Jedis getJedis() {
		Jedis jedis = null;
		try {
			jedis = RedisUtil.getJedis();
		} catch (JedisConnectionException ex) {
			logger.error("redis 服务器连接失败：", ex);
			//SystemMail.getInstance().sendText("系统报告", "redis 服务器连接失败：" + ex, "testlksy@163.com");
		}
		return jedis;
	}
	//---------------------------------------------------------------
	//-------------------------------gson转化--------------------------
	public List<Map<String, Object>> toGson(String data) {
		Gson gson = new Gson();
		return gson.fromJson(data, new TypeToken<List<Map<String, Object>>>() {}.getType());
	}

	public <T> List<T> toGson(String data, Class<T> clz) {
		Gson gson = new Gson();
		return gson.fromJson(data, new TypeToken<T>() {}.getType());
	}

	public String toJson(Object src) {
		Gson gson = new Gson();
		return gson.toJson(src);	
	}
	//----------------------------------------------------------------
	//-------------------------------一些常用工具方法--------------------------
	/**
	 * 拿到一些时间的简单调用
	 */
	public String getTimeNow() {
		return DateUtils.getNowTime();
	}

	public Timestamp getSysTimestamp() {
		return DateUtils.getSysTimestamp();
	}

	/**
	 * 拿到系统当前用户信息
	 */
	public User getCurrentUser() {
		return UserUtil.getCurrentUser();
	}
	/**
	 * 拿到IP信息
	 */
	public String getIpAddr() {
		return DataUtil.getIpAddr(getRequest());
	}
	
	/**
	 * 处理IP的信息
	 */
	public String getIPaddr() {
		return IPUtil.getIpAddress(getRequest());
	}
	
	/**
	 * 拿到天气信息
	 */
	public JSONObject getWeather(final String cityNmae) {
		String dataWather = WeatherUtils.getWeatherInform(cityNmae); // 拿到所有天气数据
		JSONObject jsonObject = JSONObject.parseObject(dataWather);
		// 请求失败
		if(jsonObject.getString("status").equals("302")) {
			return null;
		} 
		// 请求成功
		else if(jsonObject.getString("status").equals("success")) {
			JSONArray jsonArray = jsonObject.getJSONArray("results"); // 可以获取未来4天天气，我们只需要当天
			JSONObject weatherData = jsonArray.getJSONObject(0).getJSONArray("weather_data").getJSONObject(0);
			return weatherData;
		}
		return null;
	}
	/**
	 * 简单转换
	 */
	public Integer parseInt(String val) {
		return Bundle.convInt(val);
	}

	public Long parseLong(String val) {
		return Bundle.convLong(val);
	}

	public Double parseDouble(String val) {
		return Bundle.convDouble(val);
	}

	public String parseDate(String val) {
		return DateUtils.parseDate(DateUtils.yyyyMMdd, val);
	}
	
	public String parseDate(Object val) {
		return DateUtils.parseDate(DateUtils.yyyyMMddHHMMSS, val);
	}

	public String parseStr(Integer val) {
		Lists.newArrayList();
		return Bundle.convStr(val);
	}
}
